<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showAdd"
        >{{ $t('add') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="sensorName"
          clearable
          :placeholder="$t('name')"
          @change="listSensorWith"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="listSensorWith">{{ $t('search') }}</el-button>
      </el-form-item>
    </el-form>
    <div
      class="uni-scroll"
      style="height: calc(100vh - 200px)"
    >
      <el-table
        :data="sensorList"
        :empty-text="$t('not')+$t('sensor')"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <device-explain :sensor="props.row" :device="device" />
            <el-form
              style="float: right"
              label-width="130px"
              label-position="right"
              :inline="true"
            >
              <el-form-item :label="$t('delete')+$t('data')">
                <el-date-picker
                  v-model="startDate"
                  type="datetime"
                  :placeholder="$t('startDate')"
                  align="right"
                  :picker-options="pickerOptions1"
                  value-format="timestamp"
                />
                <el-date-picker
                  v-model="endDate"
                  type="datetime"
                  :placeholder="$t('endDate')"
                  align="right"
                  :picker-options="pickerOptions1"
                  value-format="timestamp"
                />
                <el-button type="danger" icon="el-icon-search" @click="delDeviceData(props.row.sensorId)">{{
                  $t('delete') }}
                </el-button>
                <el-button type="danger" icon="el-icon-search" @click="delDeviceDataAll(props.row.sensorId)">{{
                  $t('delete')+$t('all') }}
                </el-button>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column width="80" >
          <template slot-scope="scope">
            <sensor-icon :sensor="scope.row" @change="listSensorWith" />
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <div
              style="font-size:13px;height: 20px"
              class="text-gray-400"
            >
              <span class="primary-color">{{ formatSensorType(scope.row.type) }}{{ $t('port') }}:{{ scope.row.port }}</span>
              <span v-if="scope.row.sensorName!==''" style="margin-left: 3px;">{{ scope.row.sensorName }}</span>
              <span
                v-if="scope.row.status"
                style="margin-left: 3px"
              >{{ formatSensorStatus(scope.row.status) }}</span>
            </div>
            <div class="text-gray-400" style="font-size:13px;">{{ formatDate(scope.row.valueDate) }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('save')+$t('interval')+'(s)'" width="100" >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.saveInterval"
              @change="saveDataChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="hidden" :label="$t('hidden')" width="80" >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.hidden"
              @change="hiddenChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('function')"  width="600px">
          <template slot-scope="scope">
            <div>
              <el-button
                icon="el-icon-menu"
                type="primary"
                @click="gotoParam(scope.row)"
              >{{ $t('param') }}
              </el-button>
              <el-button
                icon="el-icon-menu"
                type="primary"
                @click="showCopy(scope.row)"
              >{{ $t('copy') }}
              </el-button>
              <el-button
                icon="el-icon-setting"
                type="primary"
                @click="gotoSetting(scope.row)"
              >{{ $t('setting') }}
              </el-button>

              <el-button
                type="primary"
                icon="el-icon-timer"
                @click="gotoRealTime(scope.row)"
              >{{ $t('realTime') }}
              </el-button>

              <el-button
                type="primary"
                icon="el-icon-date"
                @click="gotoHistory(scope.row)"
              >{{ $t('history') }}
              </el-button>

            </div>

            <div style="margin-top: 5px">

              <el-button
                type="primary"
                icon="el-icon-guide"
                @click="gotoExplain(scope.row)"
              >{{ $t('explain') }}
              </el-button>

              <el-button
                type="primary"
                icon="el-icon-data-line"
                :disabled="scope.row.saveInterval < 0 || scope.row.explainList.length < 1"
                @click="gotoAnalysis(scope.row)"
              >{{ $t('comparison') }}
              </el-button>

              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="click(scope.row)"
              >{{ $t('edit') }}
              </el-button>

              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="deleteSensor(scope.row)"
              >{{ $t('delete') }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :title="modalLabel"
      :visible.sync="dialogSensorFormVisible"
    >
      <el-form
        :model="sensor"
        label-width="120px"
      >
        <el-form-item :label="$t('name')">
          <el-input v-model="sensor.sensorName" />
        </el-form-item>
        <el-form-item :label="$t('icon')">
          <el-input v-model="sensor.iconUrl">
            <template slot="prepend">
              <el-image style="width: 23px;height: 23px" :src="sensor.iconUrl" />
            </template>
            <template slot="append">
              <i class="el-icon-caret-bottom" @click="choseIcon" />
            </template>
          </el-input>
          <div v-show="isIconOpen">
            <el-image
              v-for="(item,index) in iconList"
              :key="index"
              style="margin-left: 4px;cursor: pointer;width: 40px;height: 40px"
              :src="item.url"
              @click="changeIco(item.url,200145308)"
            />
          </div>
        </el-form-item>
        <el-form-item :label="$t('port')">
          <el-input v-model="sensor.port" />
        </el-form-item>
        <el-form-item :label="$t('type')">
          <el-select v-model="sensor.type">
            <el-option
              v-for="item in sensorTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSensorFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="isCopy"
    >
      <el-form
        :model="sensor"
        label-width="120px"
      >
        <el-form-item :label="$t('port')">
          <el-input v-model="sensor.port" />
        </el-form-item>
        <el-form-item :label="$t('param')">
          <el-switch v-model="sensor.withParam" />
        </el-form-item>
        <el-form-item :label="$t('setting')">
          <el-switch v-model="sensor.withSetting" />
        </el-form-item>
        <el-form-item :label="$t('explain')">
          <el-switch v-model="sensor.withExplain" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isCopy = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="copy">{{ $t('copy') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SensorIcon from '@/components/DeviceSensorIcon'
import { deleteData } from '@/api/iot/iotDeviceSensorDataApi'
import {
  failureNotice,
  successNotice,
  cancelNotice,
  listSensorType,
  formatDate,
  formatSensorType
} from '@/util/common'
import {
  listSensorWith,
  deleteSensor,
  updateSensor,
  insertSensor,
  copySensor,
  listSensorIcon
} from '@/api/iot/iotDeviceSensorApi'
import DeviceExplain from '@/components/SensorCameraList/DeviceExplain'

export default {
  name: 'SensorManage',
  components: {
    DeviceExplain,
    SensorIcon
  },
  data() {
    return {
      sensorName: null,
      isCopy: false,
      sensorTypeList: [],
      sensorList: [],
      device: {},
      serverMessage: null,
      searchName: null,

      modalLabel: null,
      sensor: {
        sensorId: null,
        sensorName: '',
        iconUrl: '',
        port: '0',
        type: 1
      },
      dialogSensorFormVisible: false,
      isIconOpen: false,
      iconList: [],
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      startDate: '',
      endDate: ''
    }
  },
  mounted() {
    this.sensorTypeList = listSensorType(this)
    const param = this.$route.query
    this.device.deviceCore = param.deviceCore
    this.device.deviceName = param.deviceName
    this.listSensorWith()
    listSensorIcon({
    }).then(res => {
      const { code } = res
      if (code === '200') {
        this.iconList = res.data
      }
    })
    this.setTagsViewTitle()
  },
  methods: {
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    formatDate(date) {
      return formatDate(this, date)
    },
    copy() {
      copySensor({
        sensorId: this.sensor.sensorId,
        withParam: this.sensor.withParam,
        withExplain: this.sensor.withExplain,
        withSetting: this.sensor.withSetting,
        port: this.sensor.port
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.isCopy = false
        this.listSensorWith()
      })
    },
    showCopy(sensor) {
      this.sensor = sensor
      sensor.withParam = false
      sensor.withExplain = true
      sensor.withSetting = true
      this.isCopy = true
    },
    gotoHistory(sensor) {
      this.$router.push({
        path: '/device/sensor/history/' + sensor.sensorId,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoRealTime(sensor) {
      this.$router.push({
        path: '/device/sensor/real-time/' + sensor.sensorId,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoParam(sensor) {
      this.$router.push({
        path: '/device/param/' + this.device.deviceCore,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoSetting(sensor) {
      this.$router.push({
        path: '/device/setting/' + this.device.deviceCore,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoExplain(sensor) {
      this.$router.push({
        path: '/device/explain/' + this.device.deviceCore,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoAnalysis(sensor) {
      this.$router.push({
        path: '/device/sensor/analysis/' + sensor.sensorId,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    formatSensorStatus(status) {
      if (status !== 'UNKNOW') {
        return '[' + this.$t(status) + ']'
      }
      return ''
    },
    delDeviceDataAll(sensorId) {
      const that = this
      this.$confirm(this.$t('delete'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteData({
            sensorId: sensorId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
            }
          })
        })
    },
    delDeviceData(sensorId) {
      const startDate = '' + this.startDate
      const endDate = '' + this.endDate
      if (startDate == null || startDate === '' || endDate == null || endDate === '') {
        failureNotice(this, this.$t('not') + this.$t('time'))
        return
      }
      const that = this
      this.$confirm(this.$t('delete'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteData({
            sensorId: sensorId,
            startTime: parseInt(startDate.substr(0, 10)),
            endTime: parseInt(endDate.substr(0, 10))
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
            }
          })
        })
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.device.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    saveDataChange(item) {
      updateSensor({
        sensorId: item.sensorId,
        saveInterval: item.saveInterval,
        deviceCore: this.device.deviceCore
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
      })
    },
    hiddenChange(item) {
      updateSensor({
        sensorId: item.sensorId,
        hidden: item.hidden,
        deviceCore: this.device.deviceCore
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
      })
    },
    showAdd() {
      this.modalLabel = this.$t('add')
      this.sensor.sensorName = ''
      this.sensor.iconUrl = ''
      this.sensor.type = 1
      this.sensor.port = '0'
      this.dialogSensorFormVisible = true
    },
    addOrUpdate() {
      if (this.sensor.iconUrl === '') {
        failureNotice(this, this.$t('icon'))
        return
      }
      if (this.sensor.port == null) {
        failureNotice(this, this.$t('port'))
        return
      }
      const json = {
        sensorName: this.sensor.sensorName,
        iconUrl: this.sensor.iconUrl,
        deviceCore: this.device.deviceCore,
        port: this.sensor.port,
        type: this.sensor.type,
        model: 'manage'
      }

      if (!this.sensor.sensorId) {
        insertSensor(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.dialogSensorFormVisible = false
          }
          this.listSensorWith()
        })
      } else {
        json.sensorId = this.sensor.sensorId
        json.port = this.sensor.port
        updateSensor(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.dialogSensorFormVisible = false
          }
          this.listSensorWith()
        })
      }
    },
    choseIcon() {
      if (this.isIconOpen) {
        this.isIconOpen = false
      } else {
        this.isIconOpen = true
      }
    },
    changeIco(iconUrl) {
      this.isIconOpen = false
      this.sensor.iconUrl = iconUrl
    },
    click(item) {
      this.sensorId = item.sensorId
      this.sensor.sensorId = item.sensorId
      this.sensor.decimal = item.decimal
      this.sensor.sensorName = item.sensorName
      this.sensor.iconUrl = item.iconUrl
      this.sensor.port = item.port
      this.sensor.type = item.type
      this.modalLabel = this.$t('update')
      this.dialogSensorFormVisible = true
    },
    deleteSensor(item) {
      const that = this
      this.$confirm(this.$t('delete') + item.sensorName, this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteSensor({
            sensorId: item.sensorId
          }).then(res => {
            that.listSensorWith()
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.device.deviceCore,
        sensorName: this.sensorName,
        withExplain: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.sensorList = data
        } else {
          this.sensorList = []
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
  @import '@/styles/element-variables.scss';

  .primary-color {
    color: $--color-primary;
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 200px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
